
// pages/live/live.js
import { reqLiveStatus } from "../../api/live"
import { getStorage } from "../../utils/storage"

import TLS from 'im-live-sells'
import TIM from 'tim-wx-sdk'
import {
  reqGetUserSig
} from '../../api/liveroom'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    start:0,
    roomId:'',
    anchorId:'',
    message:[],
    membercount:'',
    
  },

  async ensurestoplive(){
    const res = await wx.modal({content:'确认结束直播？'})

    if (res) {
      this.stoplive()
    }
  },

  handleSend(e) {
    // console.log(e.detail)
    this.tls.sendMessage(e.detail).then(res => {
      // console.log(res)
      var msg = []
      msg.push({
        name: res.nick,
        message: res.message,
        id: `id${Date.now()}`
      })
      this.setData({

        message: [...this.data.message, ...msg]
      })
    })
  },

  onLoad(){

    const roomId = getStorage('openId')
    const anchorId = getStorage('customerId')
    if (anchorId) {
      this.setData({
        anchorId: anchorId
      })
    }

    if (roomId) {
      this.setData({
        roomId: roomId
      })
    }
  },

  async initTLS() {
    // console.log('this.data:', this.data); // 检查 this.data 是否正确
    const openId = getStorage('openId');
    const roomId = this.data.roomId; // 检查 this.data.roomId 是否正确
    // console.log('roomId:', roomId);

    if (!roomId) {
      console.error('roomId is empty or undefined');
      return;
    }

    const param = {
      openId: openId
    };
    const {
      data
    } = await reqGetUserSig(param);

    this.tls = new TLS({
      SDKAppID: data.sdkappID,
      roomID: roomId,
      userSig: data.userSig,
      userName: data.userName,
      TIM: TIM
    });

    this.tls.on(TLS.EVENT.SDK_READY, async () => {
      // console.log('SDK_READY');
      // console.log('roomId before joinRoom:', roomId); // 再次检查 roomId
      const {
        groupInfo,
        userInfo
      } = await this.tls.joinRoom({
        roomID: roomId,
        getOwnerInfo: true
      });

      console.log(groupInfo,userInfo)

      this.setData({
        groupInfo:groupInfo,
        userInfo:userInfo,
        ownerInfo: groupInfo.ownerInfo,
        membercount:groupInfo.memberCount
      })

      //加入群组
      this.tls.on(TLS.EVENT.JOIN_GROUP, async (data) => {
        // console.log("加入群聊",data)
        var msg = []
        msg.push({
          name: data.nick,
          message: "进入了直播间",
          id: `id${Date.now()}`
        })
        this.setData({
          message: [...this.data.message, ...msg]
        })

        // 实时更新直播间人数
        const res = await this.tls.getGroupMemberList()
        console.log(res.data.memberList.length)
        this.setData({
          membercount:res.data.memberList.length
        })
        // console.log(this.data.message)
      })
    });

    //退出群组
    this.tls.on(TLS.EVENT.EXIT_GROUP,async()=>{
      const res = await this.tls.getGroupMemberList()
        console.log(res.data.memberList.length)
        this.setData({
          membercount:res.data.memberList.length
        })
    })

    //收到消息
    this.tls.on(TLS.EVENT.MESSAGE, async (data) => {
      // console.log(data)
      if (!data.userID) return
      var msg = []
      msg.push({
        name: data.nick,
        message: data.message,
        id: `id${Date.now()}`
      })

      this.setData({

        message: [...this.data.message, ...msg]
      })
    })
  },

  start(){
    this.setData({
      start:1
    })

    this.startlive()
  },

  async stoplive(){
    //修改主播间状态为未开播
    const status = 0
    await reqLiveStatus(status)
    
    //退出直播间
    this.tls.exitRoom().then(() => {
      console.log("该方法被执行了...")
      wx.navigateBack()
    })
  },

  async startlive(){
    const status = 1
    await reqLiveStatus(status)
    // console.log(code)
    this.initTLS()
  },

  
})